package com.reggie.task;

import com.reggie.entity.Orders;
import com.reggie.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 支付超时订单处理
     * 对于下单后超过15分钟仍未支付的订单自动修改状态为 [已取消]
     */
    @Scheduled(cron = "0 * * * * ?")//每分钟执行一次
    public void processTimeOutOrder(){
        //每分钟去查询一下订单表中的数据，然后判断订单中有没有待支付中的数据，如果有代付款的，改为取消订单
        log.info("开始进行支付超时订单处理:{}", LocalDateTime.now());
        //获取当前你时间，减去15分钟 > 下单时间，就超时了
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);

        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, time);
        if (ordersList != null && ordersList.size() > 0){
            ordersList.forEach(orders -> {
                Orders ord = Orders.builder()
                        .status(Orders.CANCELLED)
                        .id(orders.getId())
                        .cancelReason("订单支付超时，自动取消")
                        .cancelTime(LocalDateTime.now())
                        .build();
                orderMapper.updateOrdersById(ord);
            });
        }
    }

    @Scheduled(cron = "0 0 1 * * ?")// 每天凌晨1点执行一次
    public void processDeliveryOrder(){
        log.info("开始进行未完成订单状态处理:{}", LocalDateTime.now());
        //获取当前你时间，减去15分钟 > 下单时间，就超时了
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);

        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);
        if (ordersList != null && ordersList.size() > 0) {
            ordersList.forEach(orders -> {
                Orders ord = Orders.builder()
                        .status(Orders.COMPLETED)
                        .id(orders.getId())
                        .build();
                orderMapper.updateOrdersById(ord);
            });
        }
    }
}
